import React, { useRef, useState } from 'react';

import { useAntdTable } from 'ahooks';
import { Button, DatePicker, Form, InputNumber, Space, Table, Tabs, Typography } from 'antd';
import { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';

import Filter from '@/components/filter';
import NumberInput from '@/components/number-input';

import { store } from '@/store';

import { usePermission } from '@/auth';
import { proDataYearList, proDataYearSave } from '@/services/bizApi/nianshujujiekou';

import { tabItems, tableSource } from './data';

/** 该模块增删改查对象 */
export type BizObamountct = BIZAPI.ProDataYearEntity;

const Page: React.FC = () => {
  const permission = usePermission();
  const [filter] = Filter.useForm();
  const [form] = Form.useForm();
  const [tableData, setTableData] = useState<BizObamountct[]>([]);
  const [selectName, setSelectName] = useState('');
  const [selectIndex, setSelectIndex] = useState(0);
  const [refreshKey, setRefreshKey] = useState(0);
  const tabsKey = useRef('1');
  const sewageData = useRef<BizObamountct>();

  const totalArrayName = ['药剂用量(合计)', '水费(吨)', '电费(度)', '其他生产费用(日常)'];

  const agentData = useRef<BizObamountct>({
    category: totalArrayName[Number(tabsKey.current) - 1],
    ton: 0,
    amount: 0,
    agentConsumption: 0,
    amountConsumption: 0
  });
  const sewageTon = useRef<number>();
  const sewageAmount = useRef<number>();

  const table = useAntdTable(
    async () => {
      const res = await proDataYearList({
        year: filter.getFieldValue('year')?.format('YYYY') || dayjs().format('YYYY')
      });

      let backTableData = res.data!;
      if (backTableData!.length > 0) {
        //储存 污水量数据
        sewageData.current = backTableData!.filter((item) => item.category === '污水量')[0];
        //储存 药剂用量合计
        agentData.current = backTableData!.filter(
          (item) => item.category === totalArrayName[Number(tabsKey.current) - 1]
        )[0];

        form.setFieldValue('sewageTon', sewageData.current?.ton);
        form.setFieldValue('sewageAmount', sewageData.current?.amount);
        sewageTon.current = sewageData.current?.ton;
        sewageAmount.current = sewageData.current?.amount;

        backTableData = res.data!.filter(
          (item) =>
            item.category !== '污水量' &&
            item.category !== '药剂用量(合计)' &&
            item.category !== '水费(吨)' &&
            item.category !== '电费(度)'
        );
      }
      const mergeData = handlerMerge(tableSource(tabsKey.current), backTableData);

      // console.log('backTableData:', backTableData);
      // console.log('mergeData:', mergeData);
      setTableData(mergeData);

      return {
        list: tableData,
        total: backTableData?.length || 0
      };
    },
    {
      form: filter
    }
  );

  //计算	药剂吨耗(kg/吨)
  const handlerCalculateTon = (record: BizObamountct) => {
    if (sewageTon.current && record.ton) {
      const backnum = Number(((record.ton * 1000) / sewageTon.current).toFixed(3));
      record.agentConsumption = backnum;
      return backnum;
    }
    return 0;
  };

  //计算	金额吨耗(元/吨)
  const handlerCalculateAmount = (record: BizObamountct) => {
    if (sewageTon.current && record.amount) {
      const backnum = Number(((record.amount * 10000) / sewageTon.current).toFixed(3));
      record.amountConsumption = backnum;
      return backnum;
    }
    return 0;
  };

  //合并两个数组
  const handlerMerge = (array1: BizObamountct[], array2: BizObamountct[]) => {
    // 按name合并，后者的属性会覆盖前者
    return array1.map((item1) => {
      const matchingItem = array2.find((item2) => item2.category == item1.category);
      return matchingItem ? { ...matchingItem } : item1;
    });
  };

  const defaultColumns: ColumnsType<BizObamountct> = [
    {
      title: '序号',
      dataIndex: 'index',
      align: 'center',
      width: 80,
      fixed: 'left',
      render: (_, row, index) => index + 1
    },
    {
      title: '类别',
      dataIndex: 'category',
      fixed: 'left',
      width: 200
    },
    {
      title: '吨',
      dataIndex: 'ton',
      width: 200,
      render: (value: number, record: BizObamountct, index: number) => (
        <NumberInput
          edit={selectName === record.category && selectIndex === index}
          record={record}
          table={table}
          name="ton"
          value={value === 0 ? '' : value}
          onChange={(val) => {
            tableData[index]['ton'] = val as never;
            setTableData([...tableData]);
          }}
        />
      )
    },
    {
      title: '金额(万元)',
      dataIndex: 'amount',
      width: 200,
      render: (value: number, record: BizObamountct, index: number) => (
        <NumberInput
          edit={selectName === record.category && selectIndex === index}
          record={record}
          table={table}
          name="amount"
          value={value === 0 ? '' : value}
          onChange={(val) => {
            tableData[index]['amount'] = val as never;
            setTableData([...tableData]);
          }}
        />
      )
    },
    {
      title: '药剂吨耗(kg/吨)',
      dataIndex: 'agentConsumption',
      width: 200,
      render: (value: number, record: BizObamountct, index: number) => (
        <Text>{handlerCalculateTon(record)}</Text>
      )
    },
    {
      title: '	金额吨耗(元/吨)',
      dataIndex: 'amountConsumption',
      width: 200,
      render: (value: number, record: BizObamountct, index: number) => (
        <Text>{handlerCalculateAmount(record)}</Text>
      )
    }
  ];

  const onTabChange = (key: string) => {
    console.log(key);
    setRefreshKey(refreshKey + 1);
    tabsKey.current = key;
    table.refresh();
    setSelectName('');
    setSelectIndex(-1);
  };

  const onSearch = () => {
    form.setFieldsValue({
      sewageTon: undefined,
      sewageAmount: undefined
    });
    sewageData.current = undefined;
    sewageTon.current = undefined;
    sewageAmount.current = undefined;

    table.search.submit();
  };

  const onReset = () => {
    table.search.reset();
  };

  const { Text } = Typography;

  return (
    <>
      {/* 筛选 */}
      <Filter
        onReset={onReset}
        onFinish={onSearch}
        form={filter}
        extra={
          <>
            {permission.check() && (
              <Button
                onClick={async () => {
                  console.log(tableData);
                  //删除 category 是 '污水量' 的数据
                  const filterTableData = tableData.filter((item) => item.category !== '污水量');

                  filterTableData.unshift({
                    category: totalArrayName[Number(tabsKey.current) - 1],
                    year: filter.getFieldValue('year')?.format('YYYY') || dayjs().format('YYYY'),
                    ...agentData.current
                  });

                  if (sewageData.current) {
                    filterTableData.unshift({
                      ...sewageData.current,
                      ton: form.getFieldValue('sewageTon') || 0,
                      amount: form.getFieldValue('sewageAmount') || 0,
                      agentConsumption: 0,
                      amountConsumption: 0
                    });
                  } else {
                    filterTableData.unshift({
                      category: '污水量',
                      ton: form.getFieldValue('sewageTon') || 0,
                      amount: form.getFieldValue('sewageAmount') || 0,
                      agentConsumption: 0,
                      amountConsumption: 0
                    });
                  }

                  const query = filterTableData.map((item) => {
                    return {
                      ...item,
                      id: item.id,
                      year: filter.getFieldValue('year')?.format('YYYY') || dayjs().format('YYYY')
                    };
                  });
                  await proDataYearSave(query as BIZAPI.ProDataYearEntity[]);
                  store.app?.message.success('保存成功');
                  table.refresh();
                  setSelectName('');
                  setSelectIndex(-1);
                }}
                type="primary"
              >
                保存
              </Button>
            )}
          </>
        }
      >
        <Filter.Item name="year">
          <DatePicker
            picker="year"
            onChange={onSearch}
            placeholder={'请选择年份'}
            format="YYYY"
            value={filter.getFieldValue('year')}
            defaultValue={dayjs()}
          />
        </Filter.Item>
        <Filter.Item>
          <div style={{ display: 'flex', justifyContent: 'flex-start' }}>
            <div style={{ lineHeight: '32px' }}>污水量：</div>
            <Space>
              <Form form={form} name="basic" layout="inline">
                <Form.Item name="sewageTon" label="">
                  <InputNumber
                    min={0}
                    style={{ width: 160 }}
                    onChange={(val) => {
                      sewageTon.current = val as number;
                      setRefreshKey(refreshKey + 1);
                    }}
                    suffix="吨"
                  />
                </Form.Item>
                <Form.Item name="sewageAmount" label="">
                  <InputNumber
                    min={0}
                    style={{ width: 160 }}
                    onChange={(val) => {
                      sewageAmount.current = val as number;
                      setRefreshKey(refreshKey + 1);
                    }}
                    suffix="万元"
                  />
                </Form.Item>
              </Form>
            </Space>
          </div>
        </Filter.Item>
        {/* <Filter.Item>
          <Button htmlType="submit" disabled={table.loading}>
            搜索
          </Button>
        </Filter.Item>

        <Filter.Item>
          <Button onClick={onReset} disabled={table.loading}>
            重置
          </Button>
        </Filter.Item> */}
      </Filter>
      {/* end 筛选 */}

      <Tabs defaultActiveKey={tabsKey.current} items={tabItems} onChange={onTabChange} />
      {/* 表格 */}
      <Table<BizObamountct>
        key={refreshKey}
        size="small"
        columns={defaultColumns as ColumnsType<BizObamountct>}
        onRow={(record, index) => {
          return {
            onClick: (event) => {
              // 点击行的事件处理
              setSelectName(record.category!);
              setSelectIndex(index!);
            }
          };
        }}
        summary={(pageData) => {
          let totalTon = 0,
            totalAmount = 0,
            totalAgentConsumption = 0,
            totalAmountConsumption = 0;
          pageData.forEach(({ ton, amount, agentConsumption, amountConsumption }) => {
            totalTon += Number(ton);
            totalAmount += Number(amount);
            totalAgentConsumption += Number(agentConsumption);
            totalAmountConsumption += Number(amountConsumption);
          });
          agentData.current = {
            ...agentData.current,
            ton: Number(totalTon.toFixed(3)),
            amount: Number(totalAmount.toFixed(3)),
            agentConsumption: Number(totalAgentConsumption.toFixed(3)),
            amountConsumption: Number(totalAmountConsumption.toFixed(3))
          };

          return (
            <>
              <Table.Summary.Row>
                <Table.Summary.Cell index={0}></Table.Summary.Cell>
                <Table.Summary.Cell index={1}>
                  <div style={{ textAlign: 'center', fontWeight: 'bold' }}>合计</div>
                </Table.Summary.Cell>
                <Table.Summary.Cell index={2}>
                  <Text style={{ fontWeight: 'bold' }}>{Number(totalTon.toFixed(3))}</Text>
                </Table.Summary.Cell>
                <Table.Summary.Cell index={3}>
                  <Text style={{ fontWeight: 'bold' }}>{Number(totalAmount.toFixed(3))}</Text>
                </Table.Summary.Cell>
                <Table.Summary.Cell index={4}>
                  <Text style={{ fontWeight: 'bold' }}>
                    {Number(totalAgentConsumption.toFixed(3))}
                  </Text>
                </Table.Summary.Cell>
                <Table.Summary.Cell index={5}>
                  <Text style={{ fontWeight: 'bold' }}>
                    {Number(totalAmountConsumption.toFixed(3))}
                  </Text>
                </Table.Summary.Cell>
              </Table.Summary.Row>
            </>
          );
        }}
        scroll={{
          x: 'max-content'
        }}
        rowKey="id"
        bordered
        dataSource={tableData}
        // {...table.tableProps}
        pagination={false}
      />
      {/* end表格 */}
    </>
  );
};

export default Page;
